﻿using AutoMapper;
using B.S.BasicData.API.Write.Application.Command.User;
using B.S.BasicData.Domain.Entities.UserRoleMenu;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MD5Hash;
using MediatR;

namespace B.S.BasicData.API.Write.Application.Handler.User
{
    /// <summary>
    /// 添加用户信息请求命令处理类
    /// </summary>
    public class CreateUserHandler:IRequestHandler<CreateUserCommand,ApiResult<int>>
    {
        IBaseRepository<UserModel> userRep;
        IMapper mapper;

        public CreateUserHandler(IBaseRepository<UserModel> userRep, IMapper mapper)
        {
            this.userRep = userRep;
            this.mapper = mapper;
        }

        public Task<ApiResult<int>> Handle(CreateUserCommand request, CancellationToken cancellationToken)
        {
            try
            {
                ApiResult<int> res = new ApiResult<int>();

                var username=userRep.GetAll().Where(x=>x.CreateName==request.userName&&!x.IsDeleted).FirstOrDefault();
                if (username!=null)
                {
                    res.Msg = "用户名已存在";
                    res.Code=ApiEnum.Fail;
                    return Task.FromResult(res);
                }

                var entity=mapper.Map<UserModel>(request);
                entity.Password ="123";
                entity.Password = entity.Password.GetMD5();
                entity.CreateName = request.userName;
                entity.CreateDate = DateTime.Now;
                
                int r=userRep.CreateAsync(entity).Result;

                if(r>0)
                {
                    res.Msg = "创建用户信息成功";
                    res.Data = r;
                    res.Code = ApiEnum.Success;
                }
                else
                {
                    res.Msg = "创建用户信息失败";
                    res.Code = ApiEnum.Fail;
                }

                return Task.FromResult(res);

            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
